knitr::opts_chunk$set(error = TRUE)
rm(list=ls(all=TRUE))  ## Clear all
setwd("/Users/jmoutouama/Documents/EEBCourse/PhyloMeth/PhyloMeth2020")

Assignment: PhyloMeth

Week1: : Getting Started

#install.packages("ctv") #the CRAN task view package

#library(ctv) #to load the package
#install.views(c("Phylogenetics", "WebTechnologies"))
#Bioconductor is a separate repository with lots of packages for dealing with genetic data, especially nextgen data. To install this and a few initial packages:

#if (!requireNamespace("BiocManager", quietly = TRUE))
#    install.packages("BiocManager")
#BiocManager::install(version = "3.10")
#BiocManager::install("Biostrings", ask=FALSE)

##Experience with coding.
##Function to plot any order in R.
GetTrees <- function(Order) {
    library(ape)
  X <- c("red", "orange", "yellow", "green", "blue", "purple")
    result<-plot(Order, type = "c", use.edge.length = FALSE,
     edge.color = sample(X, length(bird.orders$edge)/2, replace = TRUE),
     edge.width = rep(5, length(bird.orders$edge)/2))
segments(rep(0, 6), 6.5:1.5, rep(2, 6), 6.5:1.5, lwd = 5, col = X)
text(rep(2.5, 6), 6.5:1.5, paste(X, "..."), adj = 0)
title("Fancy tree...")
    return(result)
}

#let's use the data in ape
library(ape)
## Warning: package 'ape' was built under R version 3.5.2
 data("bird.orders")
GetTrees(bird.orders)

## $type
## [1] "cladogram"
## 
## $use.edge.length
## [1] FALSE
## 
## $node.pos
## [1] 2
## 
## $node.depth
## [1] 1
## 
## $show.tip.label
## [1] TRUE
## 
## $show.node.label
## [1] FALSE
## 
## $font
## [1] 3
## 
## $cex
## [1] 1
## 
## $adj
## [1] 0
## 
## $srt
## [1] 0
## 
## $no.margin
## [1] FALSE
## 
## $label.offset
## [1] 0
## 
## $x.lim
## [1]  0.0000 36.8954
## 
## $y.lim
## [1]  1 23
## 
## $direction
## [1] "rightwards"
## 
## $tip.color
## [1] "black"
## 
## $Ntip
## [1] 23
## 
## $Nnode
## [1] 22
## 
## $root.time
## NULL
## 
## $align.tip.label
## [1] FALSE

Week2: Getting Trees and Data

## Let's use the fonction made by Brian to do so. Here I want to make a tree from  Open Tree of Life 
source("Tree from Open Source.R")
GetTreeFromOpenTree("Thunbergia")

## [1] "The taxon tree has 15 terminals and 1 internal nodes out of 13 possible, which means it is 0% resolved"
# I got here just one node. Therefore, my tree had no information


## Let's make a tree from a studies

#install.packages("devtools")
#devtools::install_github("ropensci/rotl")
library("rotl")



## Now we can run the function with P_class as input. Here p_class is any class of species (Eg. Mammalia)
GetTreeFromOpenTree <- function(p_class) {
  library(rotl)
  library(ape)
  p_class.studies <- studies_find_studies(property="ot:focalCladeOTTTaxonName",
    value=p_class)
  print(p_class.studies)
  p_class.studies.ids <- unlist(p_class.studies$study_ids)
  p_class.study1.metadata <- get_study_meta(p_class.studies[[1]][[1]])
  print(get_publication(p_class.study1.metadata))
  study_id1<-p_class.studies.ids[1]
  study_tree1<-list_trees(p_class.studies,p_class.studies.ids[1])[1]
  p_class.tree<-get_tree_ids( p_class.study1.metadata)
  p_class.study1.tree1 <- get_study_tree(study_id1, study_tree1)
  plot.phylo(p_class.study1.tree1, type="fan", cex=0.2)
  return.list <- list(p_class.tree, p_class.study1.tree1 )
  names(return.list) <- c("p_class.tree", "study1.tree")
  return(return.list)
}

GetTreeFromOpenTree("Mammalia")
##   study_ids n_trees                                              tree_ids
## 1   pg_2582       1                                              tree5988
## 2   pg_2647       2                                    tree6169, tree6170
## 3   pg_2812       2                                    tree6545, tree6546
## 4   ot_1366       1                                               Tr98763
## 5    ot_308       3                                   tree1, tree2, tree3
## 6   pg_1428       2                                    tree2855, tree2856
## 7    ot_109       1                                                 tree1
## 8   pg_2550      10 tree5513, tree5515, tree5516, tree5517, tree5518, ...
## 9    ot_755       1                                                 tree1
##   candidate study_year
## 1                 2006
## 2  tree6169       2013
## 3  tree6545       2012
## 4                 2017
## 5     tree1       2007
## 6  tree2855       2011
## 7     tree1       2012
## 8                 2004
## 9     tree1       2016
##                                                                                                                                     title
## 1                                                                                       A higher-level MRP supertree of placental mammals
## 2                                                                 The placental mammal ancestor and the post-K-Pg radiation of placentals
## 3          Joint reconstruction of divergence times and life-history evolution in placental mammals using a phylogenetic covariance model
## 4                          'Waking the undead: Implications of a soft explosive model for the timing of placental mammal diversification'
## 5                                                                                                 The delayed rise of present-day mammals
## 6                                           Impacts of the Cretaceous Terrestrial Revolution and KPg Extinction on Mammal Diversification
## 7                                                                                     Genome-scale coestimation of species and gene trees
## 8 "Building the mammalian sector of the tree of life: Combining different data and a discussion of divergence times for placental mammals
## 9                                                                  Multiple morphological clocks and total-evidence tip-dating in mammals
##                                            study_doi
## 1           http://dx.doi.org/10.1186/1471-2148-6-93
## 2          http://dx.doi.org/10.1126/science.1229237
## 3 http://dx.doi.org/10.1111/j.1558-5646.2011.01558.x
## 4      http://dx.doi.org/10.1016/j.ympev.2016.09.017
## 5              http://dx.doi.org/10.1038/nature05634
## 6          http://dx.doi.org/10.1126/science.1211028
## 7            http://dx.doi.org/10.1101/gr.141978.112
## 8                                                   
## 9           http://dx.doi.org/10.1098/rsbl.2016.0033
## [1] "Beck, R.M.D., O.R.P Bininda-Emonds, M. Cardillo, F.-G. Liu, A. Purvis. 2006. A higher-level MRP supertree of placental mammals. BMC Evolutionary Biology 6: 93."
## attr(,"DOI")
## [1] "http://dx.doi.org/10.1186/1471-2148-6-93"

## $p_class.tree
## [1] "tree5988"
## 
## $study1.tree
## 
## Phylogenetic tree with 115 tips and 113 internal nodes.
## 
## Tip labels:
##  Abrocomidae, Agoutidae, Caviidae, Hydrochaeridae, Dasyproctidae, Capromyidae, ...
## 
## Rooted; no branch lengths.

Week4: Gene Tree Species Tree

devtools::install_github("bomeara/phybase")
## Skipping install of 'phybase' from a github remote, the SHA1 (05949f49) has not changed since last install.
##   Use `force = TRUE` to force installation
library(rotl)
library(ape)
phy <- get_study_tree("ot_485", "tree1")
plot(phy, cex=0.3)

library(geiger)
## Warning: package 'geiger' was built under R version 3.5.2
phy <- drop.random(phy, Ntip(phy) - 10)
plot(phy)
axisPhylo()

library(phybase)
## Loading required package: Matrix
## 
## Attaching package: 'phybase'
## The following objects are masked from 'package:ape':
## 
##     node.height, write.dna
gene.tree <- phybase::sim.coaltree.phylo(phy, pop.size=1e-12)
plot(gene.tree)

library(phytools)
## Loading required package: maps
plot(cophylo(phy, gene.tree, cbind(sort(phy$tip.label), sort(gene.tree$tip.label))))
## Rotating nodes to optimize matching...
## Done.

## Rotating nodes to optimize matching...
## Done.

species.tree <- rcoal(7)
species.tree$edge.length <- species.tree$edge.length / (10*max(branching.times(species.tree)))
gene.tree <- phybase::sim.coaltree.phylo(species.tree)
plot(cophylo(species.tree, gene.tree, cbind(sort(species.tree$tip.label), sort(gene.tree$tip.label))))
## Rotating nodes to optimize matching...
## Done.

Week 5: See RevBayes file in the file and the output

Week 6: DiscreteCharacters

# Data from Brandley et al. (2008)
library(ape)
library(phytools)
sqData<-read.csv("brandley_table.csv")
head(sqData)
##               Species   SVL   TL   SE FLL HLL Fingers Toes
## 1 Agamodon anguliceps  74.7  8.3  3.1 0.0   0       0    0
## 2    Amphisbaena alba 474.0 40.1 12.6 0.0   0       0    0
## 3       Bipes biporus 167.2 16.0  3.6 6.1   0       5    0
## 4   Bipes caniculatus 182.5 29.6  4.5 6.5   0       4    0
## 5   Bipes tridactylus 127.5 36.0  3.7 6.0   0       3    0
## 6     Blanus cinereus 174.9 21.8  4.1 0.0   0       0    0
sqTree<-read.nexus("squamate.tre.txt")
#To get a character for “limbed” versus “limbless” we will have to create it by finding all species with all limbs of length 0.
hindLimbs<-sqData[,"HLL"]!=0
foreLimbs<-sqData[,"FLL"]!=0
limbless<-!hindLimbs & !foreLimbs
limbless
##   [1]  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
##  [13] FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [25] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE
##  [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [61] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [85] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [97] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [109] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
## [121] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
## [133]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [145] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [157] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
## [169] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
## [181] FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE
## [193] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
## [205]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [217] FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
## [229] FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE
## [241]  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE
## [253] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#Now we need to set our species names to match our tree, and assign these names to our trait vector:
speciesNames<-sqData[,1]
speciesNames
##   [1] Agamodon anguliceps              Amphisbaena alba                
##   [3] Bipes biporus                    Bipes caniculatus               
##   [5] Bipes tridactylus                Blanus cinereus                 
##   [7] Chirindia swimmertoni            Diplometopon zarudnyi           
##   [9] Geocalamus acutus                Monopeltis capensis             
##  [11] Rhineura floridana               Trogonophis wiegmanni           
##  [13] Abronia graminea                 Anguis fragilis                 
##  [15] Anniella geronimensis            Anniella pulchra                
##  [17] Barisia imbricata                Celestus enneagrammus           
##  [19] Diploglossus bilobatus           Diploglossus pleei              
##  [21] Elgaria coerulea                 Elgaria kingii                  
##  [23] Elgaria multicarinata            Elgaria panamintina             
##  [25] Elgaria paucicarinata            Gerrhonotus liocephalus         
##  [27] Mesaspis moreleti                Ophiodes striatus               
##  [29] Ophisaurus apodus                Ophisaurus attenuatus           
##  [31] Ophisaurus harti                 Ophisaurus koellikeri           
##  [33] Ophisaurus ventralis             Sauresia agasepsoides           
##  [35] Wetmorena haetiana               Chamaesaura anguina             
##  [37] Cordylus cataphractus            Cordylus cordylus               
##  [39] Cordylus jordani                 Cordylus warreni                
##  [41] Platysaurus rhodiseinsis         Pseudocordylus microlepidotus   
##  [43] Dibamus novaeguineae             Coleonyx elegans                
##  [45] Diplodactylus damaeus            Gekko gecko                     
##  [47] Gonatodes albogularis            Oedura coggeri                  
##  [49] Teratoscincus scincus            Angolosaurus skoogi             
##  [51] Cordylosaurus trivittata         Gerrhosaurus major              
##  [53] Gerrhosaurus nigrolineatus       Tetradactylus africanus         
##  [55] Tetradactylus seps               Tetradactylus tetradactylus     
##  [57] Tracheloptychus madagascariensis Zonosaurus ornatus              
##  [59] Alopoglossus atriventris         Alopoglossus carinicaudatus     
##  [61] Alopoglossus copii               Arthrosaura kockii              
##  [63] Arthrosaura reticulata           Bachia bresslaui                
##  [65] Bachia dorbignyi                 Bachia flavescens               
##  [67] Calyptommatus leiolepis          Calyptommatus nicterus          
##  [69] Calyptommatus sinebrachiatus     Cercosaura argulus              
##  [71] Cercosaura eigenmanni            Cercosaura ocellata             
##  [73] Cercosaura quadrilineata         Cercosaura schreibersii         
##  [75] Colobodactylus dalcyanus         Colobodactylus taunayi          
##  [77] Colobosaura modesta              Ecpleopus affinis               
##  [79] Gymnophthalmus leucomystax       Heterodactylus imbricatus       
##  [81] Iphisa elegans                   Leposoma percarinatum           
##  [83] Micrablepharus maximiliani       Neusticurus ecpleopus           
##  [85] Neusticurus rudis                Nothobachia ablephara           
##  [87] Pholidobolus montium             Placosoma glabellum             
##  [89] Procellosaurinus erythrocercus   Procellosaurinus tetradactylus  
##  [91] Proctoporus bolivianus           Proctoporus simoterus           
##  [93] Psilophthalmus paeminosus        Ptychoglossus brevifrontalis    
##  [95] Rhachisaurus brachylepis         Tretioscincus agilis            
##  [97] Vanzosaura rubricauda            Heloderma suspectum             
##  [99] Basiliscus basiliscus            Calotes versicolor              
## [101] Dipsosaurus dorsalis             Enyaloides laticeps             
## [103] Gambelia wislizenii              Leiocephalus carinatus          
## [105] Leiolepis belliana               Phrynocephalus versicolor       
## [107] Polychrus marmoratus             Urosaurus ornatus               
## [109] Meroles cuneirostris             Podarcis sicula                 
## [111] Psammodromus hispanicus          Takydromus smaragdinus          
## [113] Lanthanotus borneensis           Aprasia pseudopulchella         
## [115] Aprasia pulchella                Aprasia repens                  
## [117] Aprasia striolata                Delma australis                 
## [119] Delma borea                      Delma fraseri                   
## [121] Delma grayi                      Delma impar                     
## [123] Delma inornata                   Delma molleri                   
## [125] Delma nasuta                     Delma tincta                    
## [127] Lialis burtoni                   Lialis jicari                   
## [129] Pletholax gracilis               Pygopus lepidopus               
## [131] Pygopus nigriceps                Acontias litoralis              
## [133] Acontias meleagris               Acontias percivali              
## [135] Acontophiops lineatus            Amphiglossus astrolabi          
## [137] Amphiglossus igneocaudatus       Amphiglossus intermedius        
## [139] Amphiglossus macrocercus         Amphiglossus melanopleura       
## [141] Amphiglossus melanurus           Amphiglossus mouroundavae       
## [143] Amphiglossus ornaticeps          Amphiglossus punctatus          
## [145] Amphiglossus stumpffi            Amphiglossus tsaratananensis    
## [147] Amphiglossus waterloti           Anomalopus mackayi              
## [149] Anomalopus swansoni              Brachymeles gracilis            
## [151] Brachymeles talinis              Calyptotis scutirostrum         
## [153] Chalcides chalcides              Chalcides mionecton             
## [155] Chalcides ocellatus              Chalcides polylepis             
## [157] Coeranoscincus reticulatus       Ctenotus leonhardii             
## [159] Ctenotus pantherinus             Ctenotus robustus               
## [161] Egernia whitii                   Eremiascincus richardsonii      
## [163] Eugongylus rufescens             Eulamprus amplus                
## [165] Eulamprus murrayi                Eulamprus quoyii                
## [167] Eumeces schneideri               Feylinia polylepis              
## [169] Glaphyromorphus gracilipes       Glaphyromorphus isolepis        
## [171] Gnypetoscincus queenslandiae     Gongylomorphus bojeri           
## [173] Hakaria simonyi                  Hemiergis peroni                
## [175] Janetaescincus braueri           Lamprolepis smaragdina          
## [177] Lerista bipes                    Lerista bougainvillii           
## [179] Melanoseps occidentalis          Mesoscincus managuae            
## [181] Mesoscincus schwartzei           Morethia butleri                
## [183] Nangura spinosa                  Notoscincus ornatus             
## [185] Ophiomorus punctatissimus        Ophioscincus ophioscincus       
## [187] Pamelaescincus gardineri         Paracontias brocchii            
## [189] Paracontias hildebrandti         Paracontias holomelas           
## [191] Plestiodon egregius              Plestiodon elegans              
## [193] Plestiodon fasciatus             Plestiodon inexpectatus         
## [195] Plestiodon laticeps              Plestiodon longirostris         
## [197] Plestiodon lynxe                 Plestiodon obsoletus            
## [199] Plestiodon reynoldsi             Prasinohaema virens             
## [201] Proscelotes eggeli               Pygomeles braconnieri           
## [203] Saiphos equalis                  Scelotes anguineus              
## [205] Scelotes arenicolus              Scelotes bipes                  
## [207] Scelotes caffer                  Scelotes gronovii               
## [209] Scelotes kasneri                 Scelotes mirus                  
## [211] Scelotes sexlineatus             Scincopus fasciatus             
## [213] Scincus scincus                  Sepsina angolensis              
## [215] Sphenops boulengeri              Sphenops sphenopsiformis        
## [217] Tiliqua adelaidensis             Tribolonotus gracilis           
## [219] Typhlacontias brevipes           Typhlacontias punctatissimus    
## [221] Typhlosaurus caecus              Typhlosaurus lineatus           
## [223] Voeltzkowia fierinensis          Voeltzkowia lineata             
## [225] Acrochordus granulatus           Agkistrodon contortrix          
## [227] Anilius scytale                  Calabaria reinhardtii           
## [229] Candoia carinata                 Casarea dussumieri              
## [231] Causus maculatus                 Cereberus rhynchops             
## [233] Charina bottae                   Chondropython viridis           
## [235] Cylindrophis maculatus           Elaphe guttata                  
## [237] Epicrates striatus               Eryx johni                      
## [239] Exiliboa plicata                 Farancia abacura                
## [241] Leptotyphlops humilis            Loxocemus bicolor               
## [243] Micrurus fulvius                 Nerodia sipedon                 
## [245] Pareas kuangtungensis            Trachyboa boulengeri            
## [247] Tropidophis haitianus            Typhlops angolensis             
## [249] Ungaliophis continentalis        Uropeltis ceylonicus            
## [251] Xenopeltis unicolor              Shinisaurus crocodiluris        
## [253] Sphenodon punctatus              Ameiva ameiva                   
## [255] Aspidoscelis sexlineatus         Dicrodon guttulatum             
## [257] Teius teyou                      Varanus griseus                 
## [259] Lepidophyma flavimaculatum       Xantusia vigilis                
## [261] Xenosaurus grandis              
## 261 Levels: Abronia graminea Acontias litoralis ... Zonosaurus ornatus
species<-sub(" ","_",speciesNames)

#names(limbless)<-species
#Now, we can change what we are calling our character values (although TRUE & FALSE would be fine):
limbs<-sapply(limbless,function(x) if(x) 0 else 1)
class (limbs)
## [1] "numeric"
## Now we create a data frame to clean these data
limbs.data<-data.frame(species,limbs)
#library(devtools)
#devtools::install_github("phylotastic/rphylotastic")
#library(rphylotastic)
#library(geiger)


str(limbs)
##  num [1:261] 0 0 1 1 1 0 0 0 0 0 ...
CleanData <- function(phy, data) {
  library(rphylotastic)
  speciesNames<-unlist(data[,1], use.names = FALSE)
  cleaned.names.data<-taxa_resolve_names_with_gnr(speciesNames)
  cleaned.names.phy<-taxa_resolve_names_with_gnr(phy$tip.label)
  phy.cleaned.names<-phy
  phy.cleaned.names$tip.label <- cleaned.names.phy
  data.vector<-data[,2]
  names(data.vector)<-cleaned.names.data
  cleaned.data<-treedata(phy.cleaned.names,data.vector, sort=TRUE, warnings=TRUE)
  return(cleaned.data)
}

cleaned.discrete<-CleanData(sqTree,limbs.data)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |===================================================                   |  74%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |==========================================================            |  84%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |=========                                                             |  14%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |============================================                          |  64%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
## Warning in treedata(phy.cleaned.names, data.vector, sort = TRUE, warnings = TRUE): The following tips were not found in 'phy' and were dropped from 'data':
##  Gonatodes albogularis
##  Lepidophyma flavimaculatum
##  Trachyboa boulengeri
class(cleaned.discrete[[2]])
## [1] "matrix"
VisualizeData <- function(phy, data) {
   dotTree(phy,data[,1],colors=setNames(c("blue","red"),c(1,0)),type="fan",fsize=0.3,lwd=2)
}



VisualizeData(cleaned.discrete$phy,cleaned.discrete$data)

##First, let’s use parsimony to look at ancestral states:
library( phangorn)
## Warning: package 'phangorn' was built under R version 3.5.2
## 
## Attaching package: 'phangorn'
## The following objects are masked from 'package:phybase':
## 
##     treedist, upgma
data(Laurasiatherian)
cleaned.discrete.phydat<-as.phyDat(cleaned.discrete$data, type="USER", levels = c("1","0"), ambiguity="-")
cleaned.discrete.tree<-pml(cleaned.discrete$phy, cleaned.discrete.phydat)
anc.p <- ancestral.pars(cleaned.discrete$phy, cleaned.discrete.phydat, type = "MPR", cost = NULL,return = "prob")
plotAnc(cleaned.discrete.tree, anc.p, 1)

anc.ml <- ancestral.pml(pml(cleaned.discrete$phy, cleaned.discrete.phydat), type="ml")
plotAnc(cleaned.discrete.tree, anc.ml, 1)

## Yes the second tree differ from the first. it seems like the second tree has more precision. 

Week 6: Continuous character models

#install.packages("yearn")
library(ape) 
library(geiger) 
library(OUwie)
## Warning: package 'OUwie' was built under R version 3.5.2
## Loading required package: nloptr
## Loading required package: lattice
library(phytools)
#library(devtools)
#devtools::install_github("phylotastic/rphylotastic")
library(rphylotastic)
## This data come from  Brandley et al. (2008)

sqData<-read.csv("brandley_table.csv")
head(sqData)
##               Species   SVL   TL   SE FLL HLL Fingers Toes
## 1 Agamodon anguliceps  74.7  8.3  3.1 0.0   0       0    0
## 2    Amphisbaena alba 474.0 40.1 12.6 0.0   0       0    0
## 3       Bipes biporus 167.2 16.0  3.6 6.1   0       5    0
## 4   Bipes caniculatus 182.5 29.6  4.5 6.5   0       4    0
## 5   Bipes tridactylus 127.5 36.0  3.7 6.0   0       3    0
## 6     Blanus cinereus 174.9 21.8  4.1 0.0   0       0    0
sqTree<-read.nexus ("squamate.tre.txt")
plotTree(sqTree,type="fan",lwd=1,fsize=0.5)

source("resolvescientificnames.R")
CleanData <- function(phy, data) {
  speciesNames<-unlist(data[,1], use.names = FALSE)
  cleaned.names.data<-taxa_resolve_names_with_gnr(speciesNames)
  cleaned.names.phy<-taxa_resolve_names_with_gnr(phy$tip.label)
  phy.cleaned.names<-phy
  phy.cleaned.names$tip.label <- cleaned.names.phy
  data.vector<-data[,2]
  names(data.vector)<-cleaned.names.data
  cleaned.data<-treedata(phy.cleaned.names,data.vector, sort=TRUE, warnings=TRUE)
  return(cleaned.data)
}

cleaned.data<-CleanData(sqTree,sqData)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |===================================================                   |  74%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |==========================================================            |  84%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |=========                                                             |  14%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |============================================                          |  64%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
## Warning in treedata(phy.cleaned.names, data.vector, sort = TRUE, warnings = TRUE): The following tips were not found in 'phy' and were dropped from 'data':
##  Gonatodes albogularis
##  Lepidophyma flavimaculatum
##  Trachyboa boulengeri
class(cleaned.data)
## [1] "list"
str(cleaned.data)
## List of 2
##  $ phy :List of 5
##   ..$ edge       : int [1:514, 1:2] 259 260 261 262 263 264 265 266 267 268 ...
##   ..$ edge.length: num [1:514] 48.33 2.27 2.51 5.62 4.37 ...
##   ..$ Nnode      : int 257
##   ..$ root.edge  : num 0
##   ..$ tip.label  : chr [1:258] "Abronia graminea" "Acontias litoralis" "Acontias meleagris" "Acontias percivali" ...
##   ..- attr(*, "class")= chr "phylo"
##   ..- attr(*, "order")= chr "cladewise"
##  $ data: num [1:258, 1] 96.2 114 197.9 207 166.9 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:258] "Abronia graminea" "Acontias litoralis" "Acontias meleagris" "Acontias percivali" ...
##   .. ..$ : NULL
VisualizeData <- function(phy, data) {
   diagnostic<-contMap(phy, data, res=100, fsize=NULL, ftype=NULL, lwd=4, legend=NULL,
       lims=NULL, outline=TRUE, sig=3, type="phylogram", direction="rightwards",
       plot=FALSE)
   plot(diagnostic)
}

VisualizeData(cleaned.data$phy,cleaned.data$data[,1])

## Brownian motion is a stochastic model in which changes from one time to the next are random draws from a normal distribution with mean 0.0 and variance σ2 × Δt. In other words, the expected variance under Brownian motion increases linearly through time with instantaneous rate σ2.

BM2<-fitContinuous(cleaned.data$phy,cleaned.data$data[,1],model="BM") 
BM2
## GEIGER-fitted comparative model of continuous data
##  fitted 'BM' model parameters:
##  sigsq = 138.341054
##  z0 = 169.171661
## 
##  model summary:
##  log-likelihood = -1502.985290
##  AIC = 3009.970579
##  AICc = 3010.017638
##  free parameters = 2
## 
## Convergence diagnostics:
##  optimization iterations = 100
##  failed iterations = 0
##  frequency of best fit = 1.00
## 
##  object summary:
##  'lik' -- likelihood function
##  'bnd' -- bounds for likelihood search
##  'res' -- optimization iteration summary
##  'opt' -- maximum likelihood parameter estimates
#Here we see that the rate of evolution is  138.341054 in 169.171661 unit of  time. 
OU1 <- fitContinuous(cleaned.data$phy, cleaned.data$data[,1], model="OU")
## Warning in fitContinuous(cleaned.data$phy, cleaned.data$data[, 1], model =
## "OU"): Non-ultrametric tree with OU model, using VCV method.
## Warning in cache$dat - mu: Recycling array of length 1 in vector-array arithmetic is deprecated.
##   Use c() or as.vector() instead.

## Warning in cache$dat - mu: Recycling array of length 1 in vector-array arithmetic is deprecated.
##   Use c() or as.vector() instead.
par(mfcol=(c(1,2)))
plot(cleaned.data$phy, show.tip.label=FALSE)
ou.tree <- rescale(cleaned.data$phy, model="OU",0.001)
plot(ou.tree)

##These trees are slighly differents. The second tree vary according to the value of a. As a, the parameter used for transformation increase, the time for diversifation decrease
AIC.BM2 <- BM2$opt$aicc
AIC.OU1 <- OU1$opt$aicc
#one.discrete.char <-limbs 
#reconstruction.info <- ace(one.discrete.char, sqTree, type="discrete", method="ML", CI=TRUE)
#best.states <- colnames(reconstruction.info$lik.anc)[apply(reconstruction.info$lik.anc, 1, which.max)]